package controller
//存放http的处理函数

import (
	"errors"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"library/Vo"
	"library/common"
	"library/config"
	"library/model"
	"library/utils"
	"log"
)

func Register(ctx *gin.Context) {
	//表单验证由前端完成，默认请求的用户名和密码都是合法的
	name := ctx.PostForm("name")
	password := ctx.PostForm("password")
	nickName := ctx.PostForm("nickname")
	log.Println("请求的用户名和密码为：",name,password)

	db := config.GetDB()
	//查询数据库是否已存在用户
	if isHaveUser(db, name) {
		Vo.ResponseFiled(ctx, common.StatusRegisterUserHaveExist,"用户已存在")
		return
	}

	fromPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		Vo.ResponseFiled(ctx, common.StatusUnknown, "加密错误")
		return
	}
	newUser := model.User{
		Name :	name,
		Password: string(fromPassword),
		NickName: nickName,
	}
	db.Create(&newUser)

	responseData := gin.H{"user":newUser}
	Vo.ResponseSuccess(ctx, common.StatusRegisterSuccess, responseData, "注册成功")
}

func Login(ctx *gin.Context) {
	//表单验证应该在前端完成的，默认接收到参数都合法
	name := ctx.PostForm("name")
	password := ctx.PostForm("password")

	db := config.GetDB()
	//用户不存在
	var user model.User
	err := db.Where("name = ?", name).First(&user).Error
	if errors.Is(err,gorm.ErrRecordNotFound) {
		//用户不存在
		Vo.ResponseFiled(ctx, common.StatusLoginUserNotFound, "用户不存在")
		return
	}
	//验证用户名密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		//不为空，则密码错误
		Vo.ResponseFiled(ctx, common.StatusLoginPwdError, "密码错误")
		return
	}
	//验证通过，返回token
	token, err := utils.ReleaseToken(user)
	if err != nil {
		Vo.ResponseFiled(ctx, common.StatusUnknown, "token生成失败")
		log.Println("token生成失败")
		return
	}

	Vo.ResponseSuccess(ctx, common.StatusLoginSuccess, gin.H{"token":token}, "登录成功")
}

func isHaveUser(db *gorm.DB, name string) bool {
	var user model.User
	err := db.Where("name = ?", name).First(&user).Error
	if !errors.Is(err,gorm.ErrRecordNotFound) {
		return true
	}
	return false
}